package biolabs.sink

import java.awt.Color

import org.jfree.chart.ChartFactory
import org.jfree.chart.ChartFrame
import org.jfree.chart.JFreeChart
import org.jfree.chart.plot.PlotOrientation
import org.jfree.chart.plot.XYPlot
import org.jfree.data.xy.XYDataset
import org.jfree.data.xy.XYSeries
import org.jfree.data.xy.XYSeriesCollection

/**
 * A {@link Sink} that draws a chart from the data pushed into it.
 */
class ChartSink(labels: Seq[String]) extends Sink[Seq[Double]] {

	private val series = for(label <- labels) yield new XYSeries(label)
	private val dataset = new XYSeriesCollection();
	for(s <- series)
		dataset.addSeries(s)
	private val chart = createChart(dataset)
	private lazy val frame = new ChartFrame("BioLabs chart", chart)

	frame.setSize(500, 400)
	frame.setVisible(true)


	override def push(time: Long, data: Seq[Double]) = {

		if(data.length != labels.length)
			throw new IllegalArgumentException("Wrong number of values. " +
					"Found: " + data.length + ", expected: " + labels.length);

		for(i <- 0 until data.length)
			series(i).add(time, data(i))
	}

	override def flush() = {}
	override def close() = {
		frame.setVisible(false)
		frame.dispose()
	}

	def hide() = { frame.setVisible(false) }
	def show() = { frame.setVisible(true) }

	private def createChart(dataset: XYDataset): JFreeChart = {

		val chart = ChartFactory.createXYLineChart(
			null, // chart title
			"time (steps)", // x axis label
			null, // y axis label
			dataset, // data
			PlotOrientation.VERTICAL,
			true, // include legend
			true, // tooltips
			false // urls
		);
		chart.setBackgroundPaint(Color.white);
		chart.setAntiAlias(true);
		chart.setTextAntiAlias(true);
		val plot = chart.getPlot().asInstanceOf[XYPlot];
		plot.setBackgroundPaint(Color.lightGray);
		plot.setDomainGridlinePaint(Color.white);
		plot.setRangeGridlinePaint(Color.white);

		return chart
	}

}